package com.mutouren.common.mq;

import java.util.HashMap;
import java.util.Map;

import javax.jms.Connection;
import javax.jms.ConnectionFactory;
import javax.jms.JMSException;
import javax.jms.Session;

import org.apache.activemq.ActiveMQConnectionFactory;

import com.mutouren.common.log.LogManager;
import com.mutouren.common.log.Logger;

public class ActiveMQSource {
	private static Logger errorLogger = LogManager.getLogger("SystemErrorLog");
	private static Map<String, Connection> mapConnection = new HashMap<String, Connection>();
	
	public static Session createSession(String serverName, boolean transacted, int acknowledgeMode) throws JMSException {
		try {
			return getConnection(serverName).createSession(transacted, acknowledgeMode);
		} catch (JMSException t) {
			errorLogger.error(String.format("ActiveMQSource.createSession() error! server: %s", serverName), t);
			throw t;
		}
	}
	
	private synchronized static Connection getConnection(String serverName) throws JMSException {
		Connection result;
		if (mapConnection.containsKey(serverName)) {
			result = mapConnection.get(serverName);
		} else {
			ActiveMQConfig config = new ActiveMQConfig(serverName);
			result = createConnection(config);
			mapConnection.put(serverName, result);
		}
		return result;
	}

	private synchronized static Connection createConnection(ActiveMQConfig config) throws JMSException {
		String url = String.format("tcp://%s:%d", config.getIp(), config.getPort());

		ConnectionFactory contectionFactory = new ActiveMQConnectionFactory(
				config.getUserName(), config.getPassword(), url);		
		Connection connection = contectionFactory.createConnection();
		connection.start();
		return connection;
	}	
	
}
